<?php
// +----------------------------------------------------------------------
// | 中联致远服务端框架
// +----------------------------------------------------------------------
// | Copyright (c) 2018 http://www.zhongliansoft.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: tony <tanyu@zhongliansoft.com>
// +----------------------------------------------------------------------

namespace app\Manage\controller;

use app\common\controller\Manage;
use app\common\model\BookPlan as BookPlanModel;
use app\common\model\BookInfo as BookInfoModel;
use app\common\model\Config as ConfigModel;
use app\common\model\BookCommon as BookCommonModel;
use app\common\model\BookSupplyDrawDetail as BookSupplyDrawDetailModel;
use think\facade\Request;
use think\facade\Log;
use think\Db;

class BookPlan extends Manage
{

    /**
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function index()
    {
        if(Request::isAjax())
        {
            $bookPlanModel = new BookPlanModel();
            return $bookPlanModel->tableData(input('param.'));
        }
        
        $bookCommon = new BookCommonModel();
        $yearList = $bookCommon->getYears();  // 获取年度列表
        $seasonList = $bookCommon->getSeasons();  // 获取季度列表
        $deptList = $bookCommon->getDepts();  // 获取部门列表
        $dirList = $bookCommon->getDirs();  // 获取方向列表
        $this->assign('yearList', $yearList);
        $this->assign('seasonList', $seasonList);
        $this->assign('deptList', $deptList);
        $this->assign('dirList', $dirList);

        // 默认值
        $configModel = new ConfigModel();
        $year = $configModel->getYear();
        $season = $configModel->getSeason();
        $this->assign('year', $year);
        $this->assign('season', $season);

        return $this->fetch();
    }

    /**
     * 导入教材计划信息
     * @return array|mixed
     */
    public function importBookPlan()
    {
        if (Request::isPost()) {
            return null;
        }
        return $this->fetch('ImportBookPlan');
    }

    /**
     * 导入教材定价信息
     * @return array|mixed
     */
    public function importBookPrice()
    {
        if (Request::isPost()) {
            return null;
        }
        return $this->fetch('ImportBookPrice');
    }
    
    /**
     * 获取批量发放教材信息
     * @return array|mixed
     */
    public function getBookInfoByApplyId()
    {
        $id  = input('param.id', '');     // 搜索关键字

        $bookPlanModel = new BookPlanModel();
        $list = $bookPlanModel->query("call getBookInfoByApplyId('".$id."');");
        
        $result = [
            'status' => true,
            'data'   => $list[0],
            'msg'    => '查询成功'
        ];

        return $result;
    }
    
    /**
     * 获取预发放教材信息
     * @return array|mixed
     */
    public function getBookInfoByBatchDrawId()
    {
        $id  = input('param.id', '');     // 搜索关键字

        $bookPlanModel = new BookPlanModel();
        $list = $bookPlanModel->query("call getBookInfoByBatchDrawId('".$id."');");
        
        $result = [
            'status' => true,
            'data'   => $list[0],
            'msg'    => '查询成功'
        ];

        return $result;
    }
    
    /**
     * 获取补发教材信息
     * @return array|mixed
     */
    public function getBookInfoBySupplyDrawId()
    {
        $id  = input('param.id', '');     // 搜索关键字

        $bookPlanModel = new BookPlanModel();
        $list = $bookPlanModel->query("call getBookInfoBySupplyDrawId('".$id."');");
        
        $result = [
            'status' => true,
            'data'   => $list[0],
            'msg'    => '查询成功'
        ];

        return $result;
    }

    /**
     * 获取预发放退书教材信息
     * @return array|mixed
     */
    public function getBookReturnInfoByBatchDrawId()
    {
        $id  = input('param.id', '');     // 搜索关键字

        $bookPlanModel = new BookPlanModel();
        $list = $bookPlanModel->query("call getBookReturnInfoByBatchDrawId('".$id."');");
        
        $result = [
            'status' => true,
            'data'   => $list[0],
            'msg'    => '查询成功'
        ];

        return $result;
    }
    
    /**
     * 获取个人教材信息
     * @return array|mixed
     */
    public function getBookReturnInfoByReturnId()
    {
        $id  = input('param.id', '');     // 搜索关键字

        $bookPlanModel = new BookPlanModel();
        $list = $bookPlanModel->query("call getBookReturnInfoByReturnId('".$id."');");
        
        $result = [
            'status' => true,
            'data'   => $list[0],
            'msg'    => '查询成功'
        ];

        return $result;
    }

    /**
     * 编辑计划
     * @return array|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function edit()
    {
        $bookPlanModel = new BookPlanModel();

        if (Request::isPost()) {
            $input  = Request::param();
            $result = $bookPlanModel->edit($input);
            return $result;
        }

        $id  = input('param.id', '');     // 搜索关键字
 
        $bookInfo = $bookPlanModel->getBookPlanById($id);

        $this->assign('bookInfo', $bookInfo);
        return $this->fetch('edit');
    }
    
    /**
     * 复制计划
     * @return array|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function copy()
    {
        $bookPlanModel = new BookPlanModel();
        $bookInfoModel = new BookInfoModel();

        if (Request::isPost()) {
            $input  = Request::param();
            $result = $bookPlanModel->copy($input);
            return $result;
        }

        $id  = input('param.id', '');     // 搜索关键字
 
        $bookInfo = $bookPlanModel->getBookPlanById($id);
        $bookList = $bookInfoModel->getBookList();

        $this->assign('bookInfo', $bookInfo);
        $this->assign('bookList', $bookList);
        
        return $this->fetch('copy');
    }

    /**
     * 删除计划
     * @return array|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function del()
    { 
        $bookPlanModel = new BookPlanModel();
        $plan_ids = input('ids'); 
        $where[] = array('id', 'in', $plan_ids);

        // 判断教材计划是否关联补发，已关联的不允许删除
        $bookSupplyDrawDetailModel = new BookSupplyDrawDetailModel();
        $supplyDetailWhere[] = array('plan_id', 'in', $plan_ids);
        $supplyDetailList = $bookSupplyDrawDetailModel->where($supplyDetailWhere)->select();

        if(count($supplyDetailList) > 0) {
            $return_data = array(
                'status' => false,
                'msg'    => '存在计划关联补发，删除失败！',
                'data'   => $plan_ids
            );
            return $return_data;
        }

        $result = $bookPlanModel->where($where)->delete();
        if ($result) {
            $return_data = array(
                'status' => true,
                'msg'    => '删除成功',
                'data'   => $plan_ids
            );
        } else {
            $return_data = array(
                'status' => false,
                'msg'    => '删除失败',
                'data'   => $plan_ids
            );
        }
        return $return_data;
    }

    /**
     * 批量修改教材数量
     * @return array|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function batchEditNum()
    {
        $this->view->engine->layout(false);
        return $this->fetch('batchEditNum');
    }
    
    /**
     * 批量修改教材单价
     * @return array|mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function batchEditPrice()
    {
        $this->view->engine->layout(false);
        return $this->fetch('batchEditPrice');
    }
    
    public function saveBookNum()
    { 
        $bookPlanModel = new BookPlanModel();
        $plan_ids = input('ids'); 
        $plan_book_num = input('plan_book_num'); 
        $where[] = array('id', 'in', $plan_ids);

        if(!preg_match("/^[1-9][0-9]*$/", $plan_book_num)){
            $return_data = array(
                'status' => false,
                'msg'    => "数量必须输入正整数"
            ); 
            return $return_data;
        }

        $data['plan_date'] = date('Y-m-d H:i:s', time());
        $data['plan_book_num'] = $plan_book_num;
        $bookPlanModel->where($where)->data($data)->update();
 
        $return_data = array(
            'status' => true,
            'msg'    => '设置成功',
            'data'   => $plan_ids
        );
        
        \think\facade\Request::token('__ZlServer_Token__', 'sha1'); 
        return $return_data;
    }

    public function saveBookPrice()
    { 
        $bookPlanModel = new BookPlanModel();
        $plan_ids = input('ids'); 
        $plan_price = input('plan_price'); 
        $where[] = array('id', 'in', $plan_ids);

        if(!preg_match("/^[0-9]+(.[0-9]{1,2})?$/", $plan_price)){
            $return_data = array(
                'status' => false,
                'msg'    => "请正确输入金额，最多2位小数"
            ); 
            return $return_data;
        }

        $data['plan_date'] = date('Y-m-d H:i:s', time());
        $data['plan_price'] = $plan_price;
        $bookPlanModel->where($where)->data($data)->update();
 
        $return_data = array(
            'status' => true,
            'msg'    => '设置成功',
            'data'   => $plan_ids
        );
         
        return $return_data;
    }

    /**
     * 默认年度季度设置
     */
    public function setting()
    {
        $configModel = new ConfigModel();
        $data = $configModel->getAll();
        $this->assign('data', $data);

        $bookCommon = new BookCommonModel();
        $yearList = $bookCommon->getSettingYears();  // 获取年度列表
        $seasonList = $bookCommon->getSeasons();  // 获取季度列表
        $this->assign('yearList', $yearList);
        $this->assign('seasonList', $seasonList);

        return $this->fetch('setting');
    }

    public function doSettingEdit()
    {
        $result            = [
            'status' => false,
            'data'   => '',
            'msg'    => '保存失败',
        ];
        $configModel = new ConfigModel();
        
        $bookCommon = new BookCommonModel();
        $yearList = $bookCommon->getSettingYears();  // 获取年度列表
        $seasonList = $bookCommon->getSeasons();  // 获取季度列表 

        if(Request::isAjax()){
            foreach(input('param.') as $k => $v) {
                if($k == 'year') {
                    $bFindYear = false;
                    foreach($yearList as $vYear){
                        if($vYear['id'] == $v){
                            $bFindYear = true;
                        }
                    }
                    if(!$bFindYear) {
                        $result['msg'] = '年度错误';
                        return $result;
                    }
                } else if ($k == 'season') {
                    $bFindSeason = false;
                    foreach($seasonList as $vSeason){
                        if($vSeason['season_id'] == $v){
                            $bFindSeason = true;
                        }
                    }
                    if(!$bFindSeason) {
                        $result['msg'] = '季度错误';
                        return $result;
                    }
                }

                $uData['value'] = $v;
                $ret = $configModel->save($uData, ['name' => $k]);
                //如果出错，就返回，如果是没有此参数，就默认跳过
                if (!$ret) {
                    return $result;
                }
            }
            
            $result['status'] = true;
            $result['msg']    = '保存成功';
            return $result;
        }
        return $result;
    }
}